﻿
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

using Swaf;
using Swaf.BizObj;
using Swaf.BizRule;
using Swaf.Container;
using Swaf.Security;

namespace SalesForce
{
	public class SalesForceBizRules : Syrinx.BaseBizRules
	{
		public void updateSalesForceContactPostExtend(IApplication app, IRuleContext context, object resultValue, object[] inputParams)
		{
			IBizObj contact = inputParams[2] as IBizObj;
			if (contact == null)
				throw new BaseException("Invalid parameter, no contact provided");
			//Actually call salesforce webservice async because it takes time and we dont need to wait.
			context.RuleGroup.execute(context, "updateSalesForceContact", null, "", new object[]{ contact, true, false});
		}

		public void updateSalesForceContact(IApplication app, IRuleContext context, IBizObj contact, bool associateWithUser, bool createAsLead)
		{
			if (!Cmn.IsEmpty(ActiveCompany.get("settings.salesForceUserId")))
			{
				SalesForceWebService.SforceService sforce = new SalesForceWebService.SforceService();
				SalesForceWebService.LoginResult lr = sforce.login((string)ActiveCompany.get("settings.salesForceUserId"), (string)ActiveCompany.get("settings.salesForcePassword"));
				if (!lr.passwordExpired)
				{
					sforce.Url = lr.serverUrl;
					sforce.SessionHeaderValue = new SalesForce.SalesForceWebService.SessionHeader();
					sforce.SessionHeaderValue.sessionId = lr.sessionId;

                    SalesForceWebService.sObject info = null;
                    if (createAsLead)
                    {
                        SalesForceWebService.Lead c = new SalesForce.SalesForceWebService.Lead();
                        c.FirstName = (string)contact.get("firstName");
                        c.LastName = (string)contact.get("lastName");
                        c.Email = (string)contact.get("email");
                        c.Phone = (string)contact.get("phone");
                        string street = (string)contact.get("defaultAddress.street1");
                        if (!Cmn.IsEmpty(contact.get("defaultAddress.street2")))
                            street += " " + contact.get("defaultAddress.street2");
                        if (!Cmn.IsEmpty(contact.get("defaultAddress.street3")))
                            street += " " + contact.get("defaultAddress.street2");
                        c.Street = street;
                        c.City = (string)contact.get("defaultAddress.city");
                        c.State = (string)contact.get("defaultAddress.stateProvince");
                        c.PostalCode = (string)contact.get("defaultAddress.zipCode");
                        c.Country = (string)contact.get("defaultAddress.Country.englishName");
                        info = c;
                    }
                    else
                    {
                        SalesForceWebService.Contact c = new SalesForce.SalesForceWebService.Contact();
                        c.FirstName = (string)contact.get("firstName");
                        c.LastName = (string)contact.get("lastName");
                        c.Email = (string)contact.get("email");
                        c.Phone = (string)contact.get("phone");
                        string street = (string)contact.get("defaultAddress.street1");
                        if (!Cmn.IsEmpty(contact.get("defaultAddress.street2")))
                            street += " " + contact.get("defaultAddress.street2");
                        if (!Cmn.IsEmpty(contact.get("defaultAddress.street3")))
                            street += " " + contact.get("defaultAddress.street2");
                        c.MailingStreet = street;
                        c.MailingCity = (string)contact.get("defaultAddress.city");
                        c.MailingState = (string)contact.get("defaultAddress.stateProvince");
                        c.MailingPostalCode = (string)contact.get("defaultAddress.zipCode");
                        c.MailingCountry = (string)contact.get("defaultAddress.Country.englishName");
                        info = c;
                    }



					if (Cmn.IsEmpty(contact.get("salesForceId")))
					{
						SalesForceWebService.SaveResult[] rc = sforce.create(new SalesForce.SalesForceWebService.sObject[] { info });

                        if (associateWithUser)
                        {
							object salesForceId = rc[0].id == null ? "" : rc[0].id;
							contact.put("salesForceId", salesForceId);
                            app.appData.put("DA.SalesForce.UpdateSalesForceContactInfo", contact);
                        }
					}
					else
					{
                        info.Id = (string)contact.get("salesForceId");
                        SalesForceWebService.SaveResult[] rc = sforce.update(new SalesForce.SalesForceWebService.sObject[] { info });
					}
				}
			}
		}

		public IBizObj getSalesForceContactInfo(IApplication app, IRuleContext context, object resultValue, object[] inputParams)
		{
			IBizObj contact = resultValue as IBizObj;
			if (contact != null)
			{
				IBizObj sfc = app.appData.get("DA.SalesForce.GetSalesForceContactInfo", contact) as IBizObj;
				if (sfc != null)
					contact.put("salesForceId", sfc.get("salesForceId"));
			}
			return contact;
		}

        public void checkAddSalesForceContactFromArtForm(IApplication app, IRuleContext context, object resultValue, object[] inputParams)
        {
            IBizObj artFormData = inputParams[2] as IBizObj;
            if (artFormData != null)
            {
                string articleUniqueId = artFormData.get("article.uniqueId").ToString().ToLower();
                if (articleUniqueId != null && articleUniqueId.Contains("salesforce"))
                {
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml((string)artFormData.get("formData"));

                    IBizObj contact = app.bizObjMgr.create("Contact");
                    foreach (XmlAttribute att in doc.DocumentElement.Attributes)
                        if (contact.containsField(att.Name))
                            contact.put(att.Name, att.Value);
                    List<ValidationError> errors = contact.validate();
                    //TODO: Deal with validation errors.    

                    bool associateWithSiteUser = false;
                    bool createAsLead = articleUniqueId.Contains("lead");
                    context.RuleGroup.execute(context, "updateSalesForceContact", 
                        contact, associateWithSiteUser, createAsLead);

                }
            }
        }
	}
}
